package demo;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/*
 *  JDBC API 详解 Statement
 * */
public class JDBCDemo4_Statement {

    /**
     * 执行DML语句
     *
     * @throws Exception 抛出异常
     */
    @Test
    public void testDML() throws Exception {
        // 1.注册驱动  (jdk5后此步骤可省略不写)
        // Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3308/my_java?useSSL=false";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);

        // 3.定义sql
        String sql = "UPDATE account SET money =3000 WHERE id =1";

        // 4.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();

        // 5.执行sql
        int count = stmt.executeUpdate(sql); // 受影响的行数
        // System.out.println(count); // 打印
        if (count > 0) {
            System.out.println("修改成功~");
        } else {
            System.out.println("修改失败~");

        }

        // 释放资源
        stmt.close();
        conn.close();
    }

    /**
     * 执行DDL语句
     *
     * @throws Exception 抛出异常
     */
    @Test
    public void testDDL() throws Exception {
        // 1.注册驱动  (jdk5后此步骤可省略不写)
        // Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接
        String url = "jdbc:mysql://127.0.0.1:3308/my_java?useSSL=false";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);

        // 3.定义sql
        // String sql = "CREATE DATABASE if NOT EXISTS my_java2";
        String sql = "drop DATABASE my_java2";

        // 4.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();

        // 5.执行sql
        int count = stmt.executeUpdate(sql); // 执行完DDL语句，可能返回的是0
        // System.out.println(count); // 打印
        if (count > 0) {
            System.out.println("删除成功~");
        }
        System.out.println("创建失败~");

        // 释放资源
        stmt.close();
        conn.close();
    }
}
